<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess"
                            templateUrl="/excel/员工导入模板.xlsx" />
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { excelToDate } from '@/utils'
import { uploadEmployess } from '@/api/employess'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
    }
  },
  // 提供计算属性拿到 type
  computed: {
    type() {
      return this.$router.query.type
    }
  },
  methods: {
    // 导入
    async handleSuccess({ results, header }) {
      // if (this.type === 'employee') {

      // }
      const data = this.resolveExcelData(results)
      //console.log(data)
      // 封装一个函数，用于处理表格数据
      // 发请求
      await uploadEmployess(data)
      this.$message.success('导入成功')
      this.$router.back()
    },
    // 解析excel数据
    resolveExcelData(data) {
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '部门': 'departmentName'
      }
      return data.map(item => {
        const obj = {}
        for (const key in item) {
          // key:                  入职日期      手机号
          // userRelations[key]    timeOfEntry   mobile
          // obj[userRelations[key]] obj['timeOfEntry']
          if (key === '入职日期' || key === '转正日期') {
            obj[userRelations[key]] = excelToDate(item[key])
          } else {
            obj[userRelations[key]] = item[key]
          }

        }
        return obj
      })

    }
  }
}
</script>
